package com.liangtian.mdm.system.organization.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.liangtian.mdm.base.utils.DateUtils;
import com.liangtian.mdm.base.utils.ResultObject;
import com.liangtian.mdm.system.log.SysLogUtil;
import com.liangtian.mdm.system.log.model.SysLogEnum;
import com.liangtian.mdm.system.log.service.SysLogService;
import com.liangtian.mdm.system.organization.model.SysOrganization;
import com.liangtian.mdm.system.organization.service.SysOrganizationService;
import com.liangtian.mdm.system.permission.service.SysPermissionService;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

/**
 * <p>Encoding    :  UTF-8</p>
 * <p>Package Name: com.liangtian.mdm.system.controller </p>
 * <p>Project Name: chccig-dm </p>
 * <p>Copyright   :  Copyright(c) 2016 石化盈科信息技术有限责任公司 </p>
 * <p>Created Time: 2016-04-27 11:19</p>
 * <p>Description : 机构控制层 </p>
 *
 * @author : wangyq
 * @version :  1.0
 */
@Controller
@RequestMapping(value = "/sysOrganization")
public class SysOrganizationController {

    //日志打印对象
    private static Logger logger = LoggerFactory.getLogger(SysOrganizationController.class);

    //当前用户
    ////@Value("${ConstantBean.CURRENT_SESSION_USER}")
    //private String ConstantBean.CURRENT_SESSION_USER;
    //机构服务接口
    @Autowired
    SysOrganizationService sysOrganizationServiceImpl;
    //权限组织接口
    @Autowired
    SysPermissionService sysPermissionService;
    //日志服务接口对象
    @Autowired
    SysLogService sysLogServiceImpl;

    /**
     * @return 组织结构初始化页面
     * @desc 跳转至组织结构初始化页面
     */
    @RequestMapping(value = "/showOrganizationView", method = RequestMethod.GET)
    public ModelAndView showSysOrganizationView() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("system/sysOrganization/page/sysOrganization_list");
        return mav;
    }

    /**
     * @param sysOrganization 机构对象
     * @param beginDateTime   开始日期
     * @param endDateTime     结束日期
     * @return
     * @desc 根据组织机构父id查询所有组织机构，如果父Id为空查询所有组织机构
     */
    @RequestMapping(value = "/queryAllOrganizationList", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject queryAllSysOrganizationList(SysOrganization sysOrganization, String beginDateTime, String endDateTime) {
        Map<String, Object> queryParams = new HashMap<>();
        queryParams.put("length", sysOrganization.getLength());
        queryParams.put("pageNum", sysOrganization.getPageNum());
        queryParams.put("start", sysOrganization.getStart());
        queryParams.put("draw", sysOrganization.getDraw());
        if (null != sysOrganization && null != sysOrganization.getOrganizationName() && !"".equals(sysOrganization.getOrganizationName())) {
            queryParams.put("organizationName", sysOrganization.getOrganizationName());
        }
        if (null != sysOrganization.getOrganizationStatus() && null != sysOrganization.getOrganizationStatus() && !"".equals(sysOrganization.getOrganizationStatus())) {
            if (-1 != sysOrganization.getOrganizationStatus()) {
                queryParams.put("organizationStatus", sysOrganization.getOrganizationStatus());
            }
        }
        if (null != beginDateTime && !"".equals(beginDateTime)) {
            queryParams.put("beginDate", DateUtils.stringToDate(beginDateTime, "yyyy-MM-dd"));
        }
        if (null != endDateTime && !"".equals(endDateTime)) {
            queryParams.put("endDate", DateUtils.stringToDate(endDateTime, "yyyy-MM-dd"));
        }
        PageInfo pageInfo = sysOrganizationServiceImpl.queryAllOrganizationList(queryParams);
        ResultObject resultObject = new ResultObject(pageInfo, (Integer) queryParams.get("draw"));
        return resultObject;
    }

    /**
     * @return 新增页面
     * @desc 跳转至新增页面
     */
    @RequestMapping(value = "/showInsertOrganizationView", method = RequestMethod.GET)
    public ModelAndView showInsertOrganizationView() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("system/sysOrganization/page/sysOrganization_add");
        return mav;
    }

    /**
     * @param sysOrganization 机构对象
     * @return 新增结果
     * @desc 新增组织机构
     */
    @RequestMapping(value = "/insertOrganization", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject insertOrganization(SysOrganization sysOrganization, HttpServletRequest request) {

        sysOrganization.setCreateDate(new Date());
        sysOrganization.setOrganizationStatus(1l);
        sysOrganization.setOrganizationAddType(1l);
        sysOrganization.setCreateUserId(1L);
        int count = sysOrganizationServiceImpl.insertOrganization(sysOrganization);
        /*//==============================记录操作日志start===============================================
        SysLog sysLog = new SysLog();
        sysLog.setUserName(ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER).getUserName());
        sysLog.setOperationType("3");
        sysLog.setBrowserType(BrowserUtils.getBrowserName(request));
        Date date = new Date();
        sysLog.setOperationDate(date);
        if(count > 0) {
            sysLog.setOperationContent("用户【"+ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER).getUserName()+"】于"+ DateUtils.dateToString(date,"yyyy-MM-dd HH:mm:ss")+",新增机构成功");
        }else {
            sysLog.setOperationContent("用户【"+ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER).getUserName()+"】于"+ DateUtils.dateToString(date,"yyyy-MM-dd HH:mm:ss")+",新增机构失败");
        }
        sysLogServiceImpl.insertLog(sysLog);
        //==============================记录操作日志end==================================================
*/
        SysLogUtil.insertLog("新增机构",
                SysLogEnum.SYS_ORGANIZATION.getCode(), SysLogEnum.XZ.getCode(), request);
        ResultObject resultObject = new ResultObject(count, "新增成功", "新增失败");
        return resultObject;
    }

    /**
     * @param session
     * @return
     * @desc 获取组织机构树
     */
    @RequestMapping(value = "/queryOrganizationTree", method = RequestMethod.POST)
    @ResponseBody
    public String queryOrganizationTree(HttpSession session) {
        Map<String, Object> params = new HashMap<>();
        //Long organizationId = Long.parseLong(session.getAttribute("organizationId").toString());
        params.put("organizationStatus", 1l);
        List<Map<String, Object>> sysOrganizationMapList = sysOrganizationServiceImpl.queryOrganizationMapListForTree(params);
/*        JSONArray treeArray = new JSONArray();
        JSONObject jo = new JSONObject();
        jo.put("id", 0l);
        jo.put("name", "机构选择");
        jo.put("pId", "");
        jo.put("open",true);
        treeArray.add(jo);
        if(sysOrganizationMapList != null && sysOrganizationMapList.size()>0){
            for (Map map : sysOrganizationMapList){
                JSONObject obj = new JSONObject();
                obj.put("id",map.get("organizationId"));
                obj.put("pId",map.get("parentOrganizationId"));
                obj.put("name",map.get("organizationName"));
                obj.put("open",true);
                treeArray.add(obj);
            }
        }
        ResultObject resultObject = new ResultObject();
        resultObject.setData(treeArray);
        return resultObject;*/
        return JSON.toJSONString(sysOrganizationMapList);
    }

    /**
     * @param ids 机构id
     * @return 受影响的行数
     * @desc 批量删除
     */
    @RequestMapping(value = "/batchDeleteOrganization", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject batchDeleteOrganization(Long[] ids, HttpServletRequest request) {
        Map<String, Object> params = new HashMap<>();
        ResultObject resultObject = new ResultObject();
        List<Long> idsList = Arrays.asList(ids);
        params.put("idsList", idsList);
        //查询子组织结构
        List<SysOrganization> subSysSysOrganizationList = sysOrganizationServiceImpl.querySubOrganizationMapList(params);
        if (subSysSysOrganizationList != null && subSysSysOrganizationList.size() > 0) {
            resultObject.setMsg("勾选的数据包含子机构，不能删除");
            resultObject.setSuccess(false);
        } else {
            int count = sysOrganizationServiceImpl.batchDeleteOrganization(params);
            SysLogUtil.insertLog("删除机构",
                    SysLogEnum.SYS_ORGANIZATION.getCode(), SysLogEnum.SC.getCode(), request);
            //==============================记录操作日志start===============================================
            /*SysLog sysLog = new SysLog();
            sysLog.setUserName(ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER).getUserName());
            sysLog.setOperationType("5");
            sysLog.setBrowserType(BrowserUtils.getBrowserName(request));
            Date date = new Date();
            sysLog.setOperationDate(date);
            if (count >0){
                sysLog.setOperationContent("用户【"+ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER).getUserName()+"】于"+ DateUtils.dateToString(date,"yyyy-MM-dd HH:mm:ss")+",删除机构成功");
                resultObject.setSuccess(true);
                resultObject.setMsg("删除机构成功");
            }else{
                sysLog.setOperationContent("用户【"+ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER).getUserName()+"】于"+ DateUtils.dateToString(date,"yyyy-MM-dd HH:mm:ss")+",删除机构失败");
                resultObject.setSuccess(false);
                resultObject.setMsg("删除机构失败");
            }
            sysLogServiceImpl.insertLog(sysLog);*/
        }
        return resultObject;
    }

    /**
     * @param ids    机构id
     * @param status 状态
     * @return
     * @desc 启用或停用机构
     */
    @RequestMapping(value = "/editOrganizationStatus", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject editOrganizationStatus(Long[] ids, String status, HttpServletRequest request) {
        Map<String, Object> params = new HashMap<>();
        List<Long> idsList = Arrays.asList(ids);
        params.put("idsList", idsList);
        params.put("organizationStatus", status);
        int count = sysOrganizationServiceImpl.editOrganizationStatus(params);
        /*//==============================记录操作日志start===============================================
        SysLog sysLog = new SysLog();
        sysLog.setUserName(ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER).getUserName());
        sysLog.setOperationType("8");
        sysLog.setBrowserType(BrowserUtils.getBrowserName(request));
        Date date = new Date();
        sysLog.setOperationDate(date);
        if(count > 0) {
            sysLog.setOperationContent("用户【"+ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER).getUserName()+"】于"+ DateUtils.dateToString(date,"yyyy-MM-dd HH:mm:ss")+",停用或启用机构成功");
        }else {
            sysLog.setOperationContent("用户【"+ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER).getUserName()+"】于"+ DateUtils.dateToString(date,"yyyy-MM-dd HH:mm:ss")+",停用或启用机构失败");
        }
        sysLogServiceImpl.insertLog(sysLog);
        //==============================记录操作日志end==================================================
*/
        SysLogUtil.insertLog("编辑机构",
                SysLogEnum.SYS_ORGANIZATION.getCode(), SysLogEnum.BJ.getCode(), request);
        ResultObject resultObject = new ResultObject(count, "编辑状态成功", "编辑状态失败");
        return resultObject;
    }

    /**
     * @param id 机构id
     * @return 编辑页面
     * @desc 跳转至组织机构编辑页面
     */
    @RequestMapping(value = "/showUpdateOrganizationView", method = RequestMethod.GET)
    public ModelAndView showUpdateOrganizationView(Long[] id) {
        ModelAndView view = new ModelAndView();
        Map<String, Object> params = new HashMap<>();
        if (id.length > 0) {
            params.put("organizationId", id[0]);
            Map<String, Object> organization = sysOrganizationServiceImpl.queryOrganizationById(params);
            view.addObject("sysOrganization", organization);
        }
        view.setViewName("system/sysOrganization/page/sysOrganization_edit");
        return view;
    }

    /**
     * @param id 机构id
     * @return 机构权限编辑页面
     * @desc 跳转至机构权限编辑页面
     */
    @RequestMapping(value = "/showUpdateOrPermissionView", method = RequestMethod.GET)
    public ModelAndView showUpdateOrPermissionView(Long[] id) {
        ModelAndView view = new ModelAndView();
        Map<String, Object> params = new HashMap<>();
        if (id.length > 0) {
            params.put("organizationId", id[0]);
            Map<String, Object> organization = sysOrganizationServiceImpl.queryOrganizationById(params);
            view.addObject("sysOrganization", organization);
        }
        view.setViewName("system/sysOrganization/page/sysOrPermission_edit");
        return view;
    }

    /**
     * @param sysOrganization 机构对象
     * @return
     * @desc 编辑组织机构
     */
    @RequestMapping(value = "/updateOrganization", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject updateOrganization(SysOrganization sysOrganization, HttpServletRequest request) {
        int count = sysOrganizationServiceImpl.updateOrganization(sysOrganization);
        /*//==============================记录操作日志start===============================================
        SysLog sysLog = new SysLog();
        sysLog.setUserName(ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER).getUserName());
        sysLog.setOperationType("4");
        sysLog.setBrowserType(BrowserUtils.getBrowserName(request));
        Date date = new Date();
        sysLog.setOperationDate(date);
        if(count > 0) {
            sysLog.setOperationContent("用户【"+ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER).getUserName()+"】于"+ DateUtils.dateToString(date,"yyyy-MM-dd HH:mm:ss")+",编辑机构成功");
        }else {
            sysLog.setOperationContent("用户【"+ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER).getUserName()+"】于"+ DateUtils.dateToString(date,"yyyy-MM-dd HH:mm:ss")+",编辑机构失败");
        }
        sysLogServiceImpl.insertLog(sysLog);
        //==============================记录操作日志end==================================================
*/
        SysLogUtil.insertLog("编辑机构",
                SysLogEnum.SYS_ORGANIZATION.getCode(), SysLogEnum.BJ.getCode(), request);
        ResultObject resultObject = new ResultObject(count, "编辑机构成功", "编辑机构失败");
        return resultObject;
    }

    /**
     * @param sysOrganization 机构对象
     * @return
     * @desc 编辑组织机构权限
     */
    @RequestMapping(value = "/updateOrganizationPermission", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject updateOrganizationPermission(SysOrganization sysOrganization, Long[] ids, HttpServletRequest request) {
        int count = sysOrganizationServiceImpl.updateOrganizationPermission(sysOrganization, ids);
        /*//==============================记录操作日志start===============================================
        SysLog sysLog = new SysLog();
        sysLog.setUserName(ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER).getUserName());
        sysLog.setOperationType("3");
        sysLog.setBrowserType(BrowserUtils.getBrowserName(request));
        Date date = new Date();
        sysLog.setOperationDate(date);
        if(count > 0) {
            sysLog.setOperationContent("用户【"+ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER).getUserName()+"】于"+ DateUtils.dateToString(date,"yyyy-MM-dd HH:mm:ss")+",编辑机构权限成功");
        }else {
            sysLog.setOperationContent("用户【"+ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER).getUserName()+"】于"+ DateUtils.dateToString(date,"yyyy-MM-dd HH:mm:ss")+",编辑机构权限失败");
        }
        sysLogServiceImpl.insertLog(sysLog);
        //==============================记录操作日志end==================================================
*/
        SysLogUtil.insertLog("编辑机构权限",
                SysLogEnum.SYS_ORGANIZATION.getCode(), SysLogEnum.BJ.getCode(), request);
        ResultObject resultObject = new ResultObject(count, "编辑机构权限成功", "编辑机构权限失败");
        return resultObject;
    }

    /**
     * /**
     *
     * @param sysOrganization 机构对象
     * @return
     * @desc 机构同名验证
     */
    @RequestMapping(value = "/sameNameValidate", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject sameNameValidate(SysOrganization sysOrganization) {
        ResultObject resultObject = new ResultObject();
        Map<String, Object> params = new HashMap<>();
        if (null != sysOrganization.getOrganizationName() && !"".equals(sysOrganization.getOrganizationName())) {
            params.put("organizationName", sysOrganization.getOrganizationName());
        }
        if (null != sysOrganization.getOrganizationId() && !"".equals(sysOrganization.getOrganizationId())) {
            params.put("organizationId", sysOrganization.getOrganizationId());
        }
        if (null != sysOrganization.getParentOrganizationId() && !"".equals(sysOrganization.getParentOrganizationId())) {
            params.put("parentOrganizationId", sysOrganization.getParentOrganizationId());
        }
        int count = sysOrganizationServiceImpl.querySameOrganizationNameCounts(params);
        if (count > 0) {
            resultObject.setSuccess(false);
        }
        return resultObject;
    }

    /**
     * @param organizationId 机构id
     * @return
     * @throws IOException
     * @desc 获取资源树
     */
    @RequestMapping(value = "/queryPermissionTree", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject queryPermissionTree(Long[] organizationId) throws IOException {
        Map<String, Object> queryParamsMap = new HashMap<>();
        queryParamsMap.put("permissionStatus", 1);
        List<Map<String, Object>> permissionMapList = null;
        if (organizationId[0] == 0l) {
            permissionMapList = sysPermissionService.queryPermissionMapListForTree(queryParamsMap);
        } else {
            queryParamsMap.put("organizationId", organizationId[0]);
            permissionMapList = sysOrganizationServiceImpl.queryPermissionMapListForTree(queryParamsMap);
        }
        JSONArray treeArray = new JSONArray();
        JSONObject mo = new JSONObject();
        mo.put("id", 0);
        mo.put("name", "权限选择");
        mo.put("pId", "");
        mo.put("type", 0);
        mo.put("open", true);
        treeArray.add(mo);
        //构建ztree
        if (permissionMapList != null && permissionMapList.size() > 0) {
            for (Map map : permissionMapList) {
                JSONObject obj = new JSONObject();
                obj.put("id", map.get("permissionId"));
                obj.put("pId", map.get("parentPermissionId"));
                obj.put("name", map.get("permissionName"));
                obj.put("type", map.get("permissionFlag"));
                obj.put("open", true);
                treeArray.add(obj);
            }
        }
        ResultObject resultObject = new ResultObject();
        resultObject.setData(treeArray);
        return resultObject;
    }

    /**
     * @param organizationId 机构id
     * @return
     * @throws IOException
     * @desc 获取机构关联权限树
     */
    @RequestMapping(value = "/queryEditPermissionTree", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject queryEditPermissionTree(Long organizationId) throws IOException {
        Map<String, Object> queryParamsMap = new HashMap<>();
        queryParamsMap.put("permissionStatus", 1);
        List<Map<String, Object>> permissionMapList = sysPermissionService.queryPermissionMapListForTree(queryParamsMap);
        //获取所选机构拥有的权限
        JSONArray treeArray = new JSONArray();
        JSONObject mo = new JSONObject();
        mo.put("id", 0);
        mo.put("name", "权限选择");
        mo.put("pId", "");
        mo.put("type", 0);
        mo.put("open", true);
        mo.put("checked", false);
        treeArray.add(mo);
        //获取当前机构拥有的权限
        Map<String, Object> queryParams = new HashMap<>();
        queryParams.put("organizationId", organizationId);
        queryParams.put("permissionStatus", 1);
        List<Map<String, Object>> permissionOwnList = sysOrganizationServiceImpl.queryPermissionMapListForTree(queryParams);
        //构建ztree
        if (permissionMapList != null && permissionMapList.size() > 0) {
            if (null != permissionOwnList && permissionOwnList.size() > 0) {
                for (Map map : permissionMapList) {
                    boolean flag = false;
                    look:
                    for (Map m : permissionOwnList) {
                        if (m.get("permissionId") == map.get("permissionId") || m.get("permissionId").equals(map.get("permissionId"))) {
                            flag = true;
                            break look;
                        }
                    }
                    JSONObject obj = new JSONObject();
                    obj.put("id", map.get("permissionId"));
                    obj.put("pId", map.get("parentPermissionId"));
                    obj.put("name", map.get("permissionName"));
                    obj.put("type", map.get("permissionFlag"));
                    obj.put("open", true);
                    treeArray.add(obj);
                    if (flag) {
                        obj.put("checked", true);
                    } else {
                        obj.put("checked", false);
                    }
                }
            } else {
                for (Map map : permissionMapList) {
                    JSONObject obj = new JSONObject();
                    obj.put("id", map.get("permissionId"));
                    obj.put("pId", map.get("parentPermissionId"));
                    obj.put("name", map.get("permissionName"));
                    obj.put("type", map.get("permissionFlag"));
                    obj.put("checked", false);
                    obj.put("open", true);
                    treeArray.add(obj);
                }
            }
        }
        ResultObject resultObject = new ResultObject();
        resultObject.setData(treeArray);
        return resultObject;
    }
}
